<template>
  <div id="tios">
    <ul class="tio-content"></ul>
    <div class="footer" :style="{position:absoluteFixed}">
      <div id="user_face_icon">
        <img :src="defaultUrl" alt>
      </div>
      <input
        :style="{borderColor:lives.labelColor}"
        :disabled="upChat"
        id="messageText"
        @keyup.enter="sendMsg"
        :placeholder="upplaceholder"
        type="text"
      >
      <span id="btn" :style="{borderColor:lives.labelColor}" @click="sendMsg" >发送</span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tiows: "",
      tio: {},
      msg: "",
    };
  },
  computed: {
    lives(){
      return this.$store.state.liveInfo
    },
    absoluteFixed(){
      return this.$store.state.absoluteFixed
    },
    upplaceholder() {
      var placeholder = "";
      if (this.$store.state.liveInfo.chatSettings == 1) {
        placeholder = "说点什么吧...";
      } else if (this.$store.state.liveInfo.chatSettings == 0) {
        placeholder = "全员禁言中";
      }
      return placeholder;
    },
    upChat() {
      var chat = "";
      if (this.$store.state.liveInfo.chatSettings == 1) {
        chat = true;
      } else if (this.$store.state.liveInfo.chatSettings == 0) {
        chat = false;
      }
      return !chat;
    },
    defaultUrl() {
      var defaultUrl = "";
      if (sessionStorage.getItem("openid")) {
        defaultUrl = sessionStorage.getItem("headimgurl");
      } else {
        defaultUrl = localStorage.getItem("youkeImg")
      }
      return defaultUrl;
    }
  },
  methods: {
    im() {
      var self = this;
      var IMHandler = function() {
        this.onopen = function(event, ws) {
          console.log("连上了");
        };
        this.onmessage = function(event, ws) {
          var data = event.data;
          var msgBody = eval("(" + data + ")");
          var ico, imgcls, spancls, nickcls;
          var content = document.getElementsByTagName("ul")[0];
          if (msgBody.cmd == "12") {
            imgcls = "imgleft";
            spancls = "spanleft";
            nickcls = "nickleft";
            content.innerHTML +=
              '<li><img src="' +
              msgBody.fromUser.portraitUri +
              '" class="' +
              imgcls +
              '"><span class="' +
              nickcls +
              '">' +
              msgBody.fromUser.loginname +
              '</span><span class="' +
              spancls +
              '">' +
              msgBody.content +
              "</span></li>";
          }
          content.scrollTop = content.scrollHeight;
        };

        this.ping = function(ws) {
          ws.send("心跳内容");
          console.log("心跳内容");
        };
      };
      this.tios();
      var ws_protocol = "ws"; // ws 或 wss
      var ip = "106.12.87.101";
      var port = 9326;

      var heartbeatTimeout = 5000; // 心跳超时时间，单位：毫秒
      var reconnInterval = 1000; // 重连间隔时间，单位：毫秒

      var binaryType = "blob"; // 'blob' or 'arraybuffer';//arraybuffer是字节
      var handler = new IMHandler();
      var myself = 0;
      var myname = "";
      var appKey = "305dabfafg98f68";
      var appSecret = "0dd0a8e2df85cacebe59f90cefa0c97d";
      var self = this;
      //生成从minNum到maxNum的随机数
      function randomNum(minNum, maxNum) {
        switch (arguments.length) {
          case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
          case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
          default:
            return 0;
            break;
        }
      }
      function initWs() {
        var queryString = "appKey=" + appKey + "&appSecret=" + appSecret;
        var param = "";
        self.tiows = new self.tio.ws(
          ws_protocol,
          ip,
          port,
          queryString,
          param,
          handler,
          heartbeatTimeout,
          reconnInterval,
          binaryType
        );
        self.tiows.connect();
      }
      initWs();
    },
    tios() {
      var self = this;
      if (typeof this.tio == "undefined") {
        self.tio = {};
      }
      self.tio.ws = {};
      self.tio.CAMMOND = {
        COMMAND_AUTH_REQ: 3,
        COMMAND_AUTH_RESP: 4,
        COMMAND_LOGIN_REQ: 5,
        COMMAND_LOGIN_RESP: 6, //判断消息
        COMMAND_CHAT_REQ: 11,
        COMMAND_CHAT_RESP: 12,
        COMMAND_HEARTBEAT_REQ: 13
      };
      self.tio.ws = function(
        ws_protocol,
        ip,
        port,
        paramStr,
        param,
        handler,
        heartbeatTimeout,
        reconnInterval,
        binaryType
      ) {
        this.ip = ip;
        this.port = port;
        this.url = ws_protocol + "://" + ip + ":" + port;
        this.binaryType = binaryType || "arraybuffer";

        if (paramStr) {
          this.url += "?" + paramStr;
          this.reconnUrl = this.url + "&";
        } else {
          this.reconnUrl = this.url + "?";
        }
        this.reconnUrl += "tiows_reconnect=true";
        this.param = param;

        this.handler = handler;
        this.heartbeatTimeout = heartbeatTimeout;
        this.reconnInterval = reconnInterval;

        this.lastInteractionTime = function() {
          if (arguments.length == 1) {
            this.lastInteractionTimeValue = arguments[0];
          }
          return this.lastInteractionTimeValue;
        };

        this.heartbeatSendInterval = heartbeatTimeout / 2;

        this.connect = function(isReconnect) {
          var _url = this.url;
          if (isReconnect) {
            _url = this.reconnUrl;
          }
          var ws = new WebSocket(_url);
          this.ws = ws;

          ws.binaryType = this.binaryType; // 'arraybuffer'; // 'blob' or 'arraybuffer';//arraybuffer是字节
          var self = this;
          let userId = "";
          var defaultUrl = "";
          // if (localStorage.getItem("openid")) {
            userId = sessionStorage.getItem("openid");
            defaultUrl = sessionStorage.getItem("headimgurl");
          // } else if (localStorage.getItem("youkeid")) {
          //   userId = localStorage.getItem("youkeid");
          //   defaultUrl = localStorage.getItem("youkeImgurl")
          // }
          ws.onopen = function(event) {
            self.handler.onopen.call(self.handler, event, ws);
            self.lastInteractionTime(new Date().getTime());

            self.pingIntervalId = setInterval(function() {
              self.ping(self);
            }, self.heartbeatSendInterval);

            self.login(
              sessionStorage.getItem("nickname"),
              userId,
              this.$route.params.id,
              defaultUrl
            );
          };
          ws.onmessage = function(event) {
            var data = event.data;
            var msgBody = eval("(" + data + ")");
            console.log(msgBody);
            self.handler.onmessage.call(self.handler, event, ws);
            self.lastInteractionTime(new Date().getTime());
          };
          ws.onclose = function(event) {
            console.log(event);
            clearInterval(self.pingIntervalId); // clear send heartbeat task

            try {
              self.handler.onclose.call(self.handler, event, ws);
            } catch (error) {}

            self.reconn(event);
          };
          ws.onerror = function(event) {
            console.log(event);
            self.handler.onerror.call(self.handler, event, ws);
          };

          return ws;
        };

        this.reconn = function(event) {
          var self = this;
          setTimeout(function() {
            var ws = self.connect(true);
            self.ws = ws;
          }, self.reconnInterval);
        };

        this.ping = function() {
          var iv = new Date().getTime() - this.lastInteractionTime(); // 已经多久没发消息了
          // 单位：秒
          if (this.heartbeatSendInterval + iv >= this.heartbeatTimeout) {
            //this.handler.ping(this.ws)
            var m = new Object();
            m.cmd = self.tio.CAMMOND.COMMAND_HEARTBEAT_REQ;
            this.send(m);
          }
        };

        this.send = function(data) {
          if (data instanceof Object) {
            this.ws.send(JSON.stringify(data));
          } else {
            this.ws.send(data);
          }
        };
        this.login = function(name, userId, id, portraitUri) {
          var m = new Object();
          m.loginname = name;
          m.otherId = userId;
          m.groupId = id;
          m.portraitUri = portraitUri;
          m.cmd = self.tio.CAMMOND.COMMAND_LOGIN_REQ;
          this.send(m);
        };
        //发送消息到组
        this.sendGroup = function(groupId, data) {
          var m = new Object();
          m.cmd = self.tio.CAMMOND.COMMAND_CHAT_REQ;
          m.groupId = groupId;
          m.content = data;
          this.send(m);
        };
      };
    },
    /*获取时间*/
    sendMsgTime() {
      function getNow(s) {
        return s < 10 ? "0" + s : s;
      }
      var myDate = new Date();
      //获取当前年
      var year = myDate.getFullYear();
      //获取当前月
      var month = myDate.getMonth() + 1;
      //获取当前日
      var date = myDate.getDate();
      var h = myDate.getHours(); //获取当前小时数(0-23)
      var m = myDate.getMinutes(); //获取当前分钟数(0-59)
      var s = myDate.getSeconds();
      var now =
        year +
        "-" +
        getNow(month) +
        "-" +
        getNow(date) +
        " " +
        getNow(h) +
        ":" +
        getNow(m) +
        ":" +
        getNow(s);
      return now;
    },
    list() {
      let chatControlStatus = 0; //所有消息默认为已审核
      // if (this.$store.state.chatControl) {
      //   chatControlStatus = 1 //所有消息设置为未审核
      // }
      var userId = "";
      var defaultUrl = "";
      if (sessionStorage.getItem("openid")) {
        userId = sessionStorage.getItem("openid");
        defaultUrl = sessionStorage.getItem("headimgurl");
      } else if (sessionStorage.getItem("youkeid")) {
        userId = sessionStorage.getItem("youkeid");
        defaultUrl = "http://live.qiyuexinxi.com/images/defaultHead.png";
      }
      let dataObj = {
        roomId: this.$route.params.id,
        id: null,
        index: 0,
        type: 0,
        content: {
          chatContent: this.msg,
          type: 0,
          status: chatControlStatus,
          time: this.sendMsgTime()
        },
        replys: [],
        extra: "",
        user: {
          id: userId,
          name: sessionStorage.getItem("nickname"),
          portrait: defaultUrl
        }
      };
      // console.log(JSON.stringify(dataObj))
      this.$http
        .post(api.replySensorKeyWord(), dataObj, {
          header: {
            "Content-Type": "application/json;charset=UTF-8"
          }
        })
        .then(res => {
          console.log(res.data);
        });
    },
    /*获取历史聊天记录*/
    getChatList() {
      let self = this;
      this.$http
        .get(api.getInteractiveChatHistory(), {
          params: {
            type: 1, //1互动聊天，2聊天管控
            roomId: this.$route.params.id
          }
        })
        .then(res => {
          console.log(res);
        });
    },
    sendMsg(e) {
      var msg = document.getElementById("messageText");
      if (msg.value.trim() == "") {
      } else {
        this.tiows.sendGroup(this.$route.params.id, msg.value);
        msg.value = "";
      }
    },
    clearMsg() {
      document.getElementById("contentId").innerHTML = "";
    }
  }
};
</script>

<style lang="less" rel=stylesheet/less scoped="scoped">
#tios {
  width: 100%;
  height: 100%;
  background: #fff;
  position: relative;
  .footer {
    width: 100%;
    height: 40px;
    background: #fff;
    bottom: 0;
    padding: 5px;
    display: flex;
    z-index: 10;
    input {
      height: 40px;
      margin: 0 5px;
      outline: none;
      text-indent: 10px;
      border-radius: 6px;
      border: 1px solid;
    }
    span {
      width: 62px;
      height: 40px;
      background: #fff;
      line-height: 40px;
      cursor: pointer;
      text-align: center;
      border-radius: 6px;
      border:1px solid;
    }
  }
}

#user_face_icon {
  width: 40px;
  height: 40px;
  img {
    border-radius: 30px;
    width: 40px;
    height: 40px;
  }
}
.imgleft {
  width: 40px;
  height: 40px;
  border-radius: 40px;
}
.tio-content {
  font-size: 14px;
  width: 100%;
  padding-bottom: 10px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;/*解决ios滚动不流畅*/
  overflow-x: hidden;
  word-break:break-all;
  word-wrap:break-word;
  li {
    margin-top: 10px;
    padding-left: 10px;
    display: block;
    clear: both;
    overflow: hidden;
    text-align: left;
    img {
      float: left;
    }
    span {
      background: #7cfc00;
      padding: 10px;
      border-radius: 10px;
      float: left;
      margin: 6px 10px 0 10px;
      width:calc(100% - 90px);
      border: 1px solid #ccc;
      box-shadow: 0 0 3px #ccc;
    }
  }
}
.tio-content li img.imgleft {
  float: left;
}
.tio-content li img.imgright {
  float: right;
}
.tio-content li span.nickleft {
  float: left;
  background: #fff;
  padding: 0px;
  border-radius: 0px;
  margin: 6px 10px 0 10px;
  // max-width: 310px;
  border: 0px solid #ccc;
  box-shadow: 0 0 0px #ccc;
  // width: 90%;
  text-align: left;
  font-size: 14px;
  color: #aaa;
}
.tio-content li span.nickright {
  float: right;
  background: #fff;
  padding: 0px;
  border-radius: 0px;
  margin: 6px 10px 0 10px;
  max-width: 310px;
  border: 0px solid #ccc;
  box-shadow: 0 0 0px #ccc;
  width: 90%;
  text-align: right;
  font-size: 14px;
  color: #aaa;
}
.tio-content li div.sysinfo {
  font-size: 14px;
  border-radius: 5px;
  background: #ddd;
  color: #fff;
  text-align: center;
  width: auto;
}
.tio-content li span.spanleft {
  float: left;
  background: #fff;
}
.tio-content li span.spanright {
  float: right;
  background: #7cfc00;
}
</style>
